package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.ArticleReplyService;
import com.example.forum.services.ArticleService;
import com.example.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Resource
    ArticleReplyService articleReplyService;
    @Resource
    ArticleService articleService;

    /**
     * 发表文章评论
     *
     * @param request
     * @param articleId
     * @param content
     * @return
     */
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, Long articleId, String content) {
        //验证的登录信息
        HttpSession session = request.getSession(false);
        if (session == null) {
            //没有登陆
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (articleId == null || articleId <= 0) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if (StringUtil.isEmpty(content)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //获取文章
        Article article = articleService.selectById(articleId);

        //设置默认值！
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        //评论贴
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReplyService.create(articleReply);
        return AppResult.success();
    }

}
